//
//  XZMyGroupDetailVC.m
//  Teecloud
//
//  Created by PC on 2018/10/26.
//  Copyright © 2018年 小志. All rights reserved.
//
#import "XZRuleVC.h"
#import "XZMyGroupDetailVC.h"
#import "XZMemberListVC.h"
#import "GMVoiceListModel.h"
#import "XZPunchCardVC.h"
#import "XZSigninQRcodeVC.h"
#import "XZMakeARollVC.h"
#import "XZLeaveApplyVC.h"
#import "XZMessageConsultVC.h"
#import "XZMachineModeVC.h"
#import "XZMachineModeMyselfVC.h"
#import "XZRuleMyselfVC.h"
#import "XZGroupDetailPopVC.h"
#import "GMReadPDFVC.h"
#import "GMExercisesVC.h"
#import "GMExaminationVC.h"
#import "GMCoursePackageVC.h"

#import "GMBuyFile.h"
#import "GMBuyVideoVC.h"
#import "XZNewsCaseVC.h"
#import "XZGroupIntroduceVC.h"
#import "GMPlayerViewController.h"
//View
#import "YBPopupMenu.h"
#import "GMMyClassCell.h"
#import "XZGroupResListCell.h"
#import "XZMemberCheckMsgCell.h"
#import "XZMyGroupDetailHeadView.h"
//Model
#import "XZResList.h"
#import "XZGroupData.h"
#import "XZBannerTops.h"
#import "XZMemberCheckMsg.h"


#import "YYFPSLabel.h"
@interface XZMyGroupDetailVC ()<YBPopupMenuDelegate,UITableViewDataSource,UITableViewDelegate,GroupDetailHeadViewDelegate,SFSafariViewControllerDelegate>
@property (nonatomic, assign) BOOL showResList;
@property (nonatomic, strong) XZGroupData *model;
@property (nonatomic, assign) NSInteger pageIndex;
@property (nonatomic, strong) NSMutableArray *msgArray;
@property (nonatomic, strong) NSMutableArray *menuIconArray;
@property (nonatomic, strong) NSMutableArray *menuTitleArray;

@property (nonatomic, strong) UITableView *tabView;
@property (nonatomic, strong) XZMyGroupDetailHeadView *headView;
@property (nonatomic, strong) YYFPSLabel *fpsLabel;
@end
#define RESLISTCELL @"GMMyClassCell"
#define MSGCELL @"XZMemberCheckMsgCell"
@implementation XZMyGroupDetailVC
- (void)dealloc{
     XZLog(@"%s",__FUNCTION__);
    [[NSNotificationCenter defaultCenter]removeObserver:self name:@"updatagroupMSG" object:nil];
   
}
////测试帧数
//- (void)testFPSLabel {
//    _fpsLabel = [YYFPSLabel new];
//    _fpsLabel.frame = CGRectMake(100, 100, 100, 50);
//    [_fpsLabel sizeToFit];
//    _fpsLabel.backgroundColor = kBlackColor;
//    [self.view addSubview:_fpsLabel];
//
//}
- (void)viewDidLoad {
    [super viewDidLoad];
    self.title = self.titleStr;
    self.view.backgroundColor= kWhiteColor;
    [self addRightBarButtonWithFirstImage:[UIImage imageNamed:@"dir-white-64"] action:@selector(menuButtonAction:)];
    [self addLeftBarButtonWithImage:[UIImage imageNamed:@"left-white-64"] action:@selector(left_BarButtonItemAction)];

    //监听消息提交回来刷新列表
    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(getGroupData) name:@"updatagroupMSG" object:nil];
    [self getGroupData];
}
- (void)left_BarButtonItemAction {
    if (kIsEmptyString(self.typeStr)) {
        [self.navigationController popViewControllerAnimated:YES];
    }else{
        [self.navigationController popToRootViewControllerAnimated:YES];
    }
}

#pragma mark - Networking
/**
 退出社团
 */
- (void)exitGroup{
    NSMutableDictionary *dict = [NSMutableDictionary dictionary];
    [dict setValue:FROM_IOS forKey:@"from"];
    [dict setValue:[XGMArchiverTools cacheForKey:BUSIORGID] forKey:@"busiOrgId"];
    [dict setValue:[XGMArchiverTools cacheForKey:USER_UserId] forKey:@"userId"];
    [dict setValue:[XGMArchiverTools cacheForKey:USER_identifierNumber] forKey:@"loginFinger"];
    [dict setValue:self.groupId forKey:@"groupId"];
    kWeakObject(self)
    [MBProgressHUD showHUDAddedTo:self.view animated:YES];
    [HJNetwork POSTWithURL:[NSString stringWithFormat:@"ajax-api.ashx?$c=TeeyunApp&$m=PostExitGroup&$v=%@",VERSION] parameters:dict cachePolicy:HJCachePolicyIgnoreCache callback:^(id responseObject, NSError *error) {
        [MBProgressHUD hideHUDForView:weakself.view animated:YES];
        if (!error) {
            if ([[responseObject objectForKey:RESULT_NAME_Success] boolValue]) {
                [weakself.navigationController popViewControllerAnimated:true];
            }else{
                [MBProgressHUD showErrorOrSuc:[responseObject objectForKey:RESULT_NAME_Message] toView:weakself.view];
            }
        }else{
            [MBProgressHUD showErrorOrSuc:@"网络异常" toView:weakself.view];
        }
    }];
}
- (void)getGroupData{
    NSMutableDictionary *dict = [NSMutableDictionary dictionary];
    [dict setValue:FROM_IOS forKey:@"from"];
    [dict setValue:[XGMArchiverTools cacheForKey:BUSIORGID] forKey:@"busiOrgId"];
    [dict setValue:[XGMArchiverTools cacheForKey:USER_UserId] forKey:@"userId"];
    [dict setValue:[XGMArchiverTools cacheForKey:USER_identifierNumber] forKey:@"loginFinger"];
    [dict setValue:self.groupId forKey:@"groupId"];
    [dict setValue:@(0) forKey:@"pageIndex"];
    
    kWeakObject(self)
    [MBProgressHUD showHUDAddedTo:self.view animated:YES];
    [HJNetwork POSTWithURL:[NSString stringWithFormat:@"ajax-api.ashx?$c=TeeyunApp&$m=GetGroupData&$v=%@",VERSION] parameters:dict cachePolicy:HJCachePolicyIgnoreCache callback:^(id responseObject, NSError *error) {
        [weakself.tabView.mj_header endRefreshing];
        [MBProgressHUD hideHUDForView:weakself.view animated:YES];
        if (!error) {
            if ([[responseObject objectForKey:RESULT_NAME_Success] boolValue]) {
                NSDictionary *dataInfo = [responseObject objectForKey:RESULT_NAME_Data];
                XZGroupData *model = [XZGroupData mj_objectWithKeyValues:dataInfo];
                //超过3条，只显示前3条，其他隐藏
                if (model.ResList.count >3) {
                    self.showResList = YES;
                }
                weakself.model = model;
                [weakself.msgArray removeAllObjects];
                [weakself.msgArray addObjectsFromArray:model.MsgList];
                //Banner有数据再设置tableHeaderView
                if (model.Tops.count > 0) {
                    weakself.tabView.tableHeaderView = weakself.headView;
                    weakself.headView.Tops = model.Tops;
                }
                [weakself.tabView reloadData];
//                [weakself testFPSLabel];
            }else{
                
                [MBProgressHUD showErrorOrSuc:[responseObject objectForKey:RESULT_NAME_Message] toView:weakself.view];
            }
            
        }else{
            [MBProgressHUD showErrorOrSuc:@"网络异常" toView:weakself.view];
        }
    }];
}
#pragma mark - MJRefresh
- (void)getGroupMsgList{
    self.pageIndex = 0;
    NSMutableDictionary *dict = [NSMutableDictionary dictionary];
    [dict setValue:FROM_IOS forKey:@"from"];
    [dict setValue:[XGMArchiverTools cacheForKey:BUSIORGID] forKey:@"busiOrgId"];
    [dict setValue:[XGMArchiverTools cacheForKey:USER_UserId] forKey:@"userId"];
    [dict setValue:[XGMArchiverTools cacheForKey:USER_identifierNumber] forKey:@"loginFinger"];
    [dict setValue:self.groupId forKey:@"groupId"];
    [dict setValue:@(self.pageIndex) forKey:@"pageIndex"];
    kWeakObject(self)
    [MBProgressHUD showHUDAddedTo:self.view animated:YES];
    [HJNetwork POSTWithURL:[NSString stringWithFormat:@"ajax-api.ashx?$c=TeeyunApp&$m=GetGroupMsgList&$v=%@",VERSION] parameters:dict cachePolicy:HJCachePolicyIgnoreCache callback:^(id responseObject, NSError *error) {
        [weakself.tabView.mj_header endRefreshing];
        [MBProgressHUD hideHUDForView:weakself.view animated:YES];
        if (!error) {
            if ([[responseObject objectForKey:RESULT_NAME_Success] boolValue]) {
                NSArray *array = [XZMemberCheckMsg mj_objectArrayWithKeyValuesArray: [responseObject objectForKey:RESULT_NAME_Data]];
                [weakself.msgArray removeAllObjects];
                [weakself.msgArray addObjectsFromArray:array];
                if (array.count == 0 && self.model.Tops.count == 0 && self.model.ResList.count == 0) {
                    [weakself.tabView setupEmptyDataText:@"暂无数据" secoundText:@"" buttonTit:@"" verticalOffset:0 emptyImage:NODATAIMG tapBlock:^{
                        
                    } butClick:^{
                        
                    }];
                }
                [weakself.tabView reloadData];
            }else{
                
                [MBProgressHUD showErrorOrSuc:[responseObject objectForKey:RESULT_NAME_Message] toView:weakself.view];
            }
            
        }else{
            [MBProgressHUD showErrorOrSuc:@"网络异常" toView:weakself.view];
        }
    }];
}
- (void)getMoreGroupMsgList{
    self.pageIndex ++;
    NSMutableDictionary *dict = [NSMutableDictionary dictionary];
    [dict setValue:FROM_IOS forKey:@"from"];
    [dict setValue:[XGMArchiverTools cacheForKey:BUSIORGID] forKey:@"busiOrgId"];
    [dict setValue:[XGMArchiverTools cacheForKey:USER_UserId] forKey:@"userId"];
    [dict setValue:[XGMArchiverTools cacheForKey:USER_identifierNumber] forKey:@"loginFinger"];
    [dict setValue:self.groupId forKey:@"groupId"];
    [dict setValue:@(self.pageIndex) forKey:@"pageIndex"];
    kWeakObject(self)
    [HJNetwork POSTWithURL:[NSString stringWithFormat:@"ajax-api.ashx?$c=TeeyunApp&$m=GetGroupMsgList&$v=%@",VERSION] parameters:dict cachePolicy:HJCachePolicyIgnoreCache callback:^(id responseObject, NSError *error) {
        [MBProgressHUD hideHUDForView:weakself.view animated:YES];
        if (!error) {
            if ([[responseObject objectForKey:RESULT_NAME_Success] boolValue]) {
                NSArray *array = [XZMemberCheckMsg mj_objectArrayWithKeyValuesArray: [responseObject objectForKey:RESULT_NAME_Data]];
                [weakself.msgArray addObjectsFromArray:array];
                if (array.count>0) {
                    [weakself.tabView.mj_footer endRefreshing];
                    [weakself.tabView.mj_header endRefreshing];
                    [weakself.tabView reloadData];
                }else{//没有数据的时候就显示暂无数据
                    weakself.tabView.mj_footer.state = MJRefreshStateNoMoreData;
                }
                
            }else{
                [weakself.tabView.mj_footer endRefreshing];
                [weakself.tabView.mj_header endRefreshing];
                [MBProgressHUD showErrorOrSuc:[responseObject objectForKey:RESULT_NAME_Message] toView:weakself.view];
            }
        }else{
            [weakself.tabView.mj_footer endRefreshing];
            [weakself.tabView.mj_header endRefreshing];
            [MBProgressHUD showErrorOrSuc:@"网络异常" toView:weakself.view];
        }
    }];
}
//菜单按钮
- (void)menuButtonAction:(UIButton *)sender{
    if (self.model.GroupConfig) {
        
        [self.menuTitleArray removeAllObjects];
        [self.menuIconArray removeAllObjects];
        
        [self.menuIconArray addObject:@"menu-member-white-128"];
        [self.menuTitleArray addObject:@"成员名单"];
        
        if ([self.model.GroupConfig.TimeType integerValue] == 1) {
            [self.menuIconArray addObject:@"menu-time-white-128"];
            [self.menuTitleArray addObject:@"考勤打卡"];
        }
        
        if ([self.model.GroupConfig.TimeType integerValue] == 2 && self.model.GroupConfig.IsManageRole) {
            [self.menuIconArray addObject:@"menu-qrcode-white-128"];
            [self.menuTitleArray addObject:@"签到二维码"];
        }
        
        if (self.model.GroupConfig.IsManageRole) {
            [self.menuIconArray addObject:@"menu-naming-white-128"];
            [self.menuTitleArray addObject:@"随堂点名"];
        }
        
        if (!self.model.GroupConfig.IsManageRole) {
            [self.menuIconArray addObject:@"menu-apply-white-128"];
            [self.menuTitleArray addObject:@"请假申请"];
        }
        
        [self.menuIconArray addObject:@"menu-query-white-128"];
        [self.menuTitleArray addObject:@"考勤查询"];
        
        [self.menuIconArray addObject:@"menu-message-white-128"];
        [self.menuTitleArray addObject:@"消息查询"];
        
        
        if ([self.model.GroupConfig.TimeType integerValue] == 2 && !self.model.GroupConfig.IsManageRole) {
            [self.menuIconArray addObject:@"menu-exit-white-128"];
            [self.menuTitleArray addObject:@"退出社团"];
        }
        
        [YBPopupMenu showRelyOnView:sender titles:self.menuTitleArray icons:self.menuIconArray menuWidth:130 delegate:self];
    }
}
#pragma mark - YBPopupMenuDelegate
- (void)ybPopupMenuDidSelectedAtIndex:(NSInteger)index ybPopupMenu:(YBPopupMenu *)ybPopupMenu{
    NSString *title = self.menuTitleArray[index];
    [self muneSkipController:title model:self.model];
}
- (void)muneSkipController:(NSString *)title model:(XZGroupData*)model{
    if ([title isEqualToString:@"成员名单"]) {
        XZMemberListVC *memberListVC = [[XZMemberListVC alloc]init];
        memberListVC.title = self.titleStr;
        memberListVC.groupId = self.groupId;
        memberListVC.model = model.GroupConfig;
        [self.navigationController pushViewController:memberListVC animated:true];
    }else if ([title isEqualToString:@"考勤打卡"]){
        XZPunchCardVC *punchCardVC = [[XZPunchCardVC alloc]init];
        punchCardVC.groupId = self.groupId;
        [self.navigationController pushViewController:punchCardVC animated:true];
    }else if ([title isEqualToString:@"签到二维码"]){
        XZSigninQRcodeVC *signinQRcodeVC = [[XZSigninQRcodeVC alloc]init];
        signinQRcodeVC.groupId = self.groupId;
        [self.navigationController pushViewController:signinQRcodeVC animated:true];
    }else if ([title isEqualToString:@"随堂点名"]){
        XZMakeARollVC *makeARollVC = [[XZMakeARollVC alloc]init];
        makeARollVC.groupId = self.groupId;
        makeARollVC.model = model.GroupConfig;
        [self.navigationController pushViewController:makeARollVC animated:true];
    }else if ([title isEqualToString:@"请假申请"]){
        XZLeaveApplyVC *leaveApplyVC = [[XZLeaveApplyVC alloc]init];
        leaveApplyVC.groupId = self.groupId;
        leaveApplyVC.model = model.GroupConfig;
        [self.navigationController pushViewController:leaveApplyVC animated:true];
    }else if ([title isEqualToString:@"考勤查询"]){
        [self inquireCheckOnWorkAttendance:model];
    }else if ([title isEqualToString:@"消息查询"]){
        XZMessageConsultVC *messageConsultVC = [[XZMessageConsultVC alloc]init];
        messageConsultVC.groupId = self.groupId;
        messageConsultVC.model = model.GroupConfig;
        [self.navigationController pushViewController:messageConsultVC animated:true];
        
    }else if ([title isEqualToString:@"退出社团"]){
        kWeakObject(self)
        UIAlertController* alert = [UIAlertController alertControllerWithTitle:@"确定退出？"
                                                                       message:@"退出后你从本社团获取的资源将不可用，确定要退出吗？"
                                                                preferredStyle:UIAlertControllerStyleAlert];
        
        UIAlertAction* confirmAction = [UIAlertAction actionWithTitle:@"确认" style:UIAlertActionStyleDefault
                                                              handler:^(UIAlertAction * action) {
                                                                  //确认退出
                                                                  [weakself exitGroup];                         }];
        UIAlertAction* cancelAction = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel
                                                             handler:^(UIAlertAction * action) {
                                                                 //取消
                                                                 
                                                             }];
        [alert addAction:cancelAction];
        [alert addAction:confirmAction];
        [self presentViewController:alert animated:YES completion:nil];
        
    }
}

/**
 考勤查询
 GroupConfig.TimeType=1时：
 GroupConfig.IsManageRole=true ->“主页 - 我的社团/小组 - 考勤查询（规律模式）”
 GroupConfig.IsManageRole=false ->“主页 - 我的社团/小组 - 考勤查询 (规律模式 - 个人)”
 
 GroupConfig.TimeType=2时：
 GroupConfig.IsManageRole=true  -> 到“主页 - 我的社团/小组 - 考勤查询（机动模式）”
 GroupConfig.IsManageRole=false ->跳转到“主页 - 我的社团/小组 - 考勤查询 (机动模式 - 个人)”
 @param model 模型
 */
- (void)inquireCheckOnWorkAttendance:(XZGroupData *)model{
    if ([model.GroupConfig.TimeType integerValue] == 1) {
        if (!model.GroupConfig.IsManageRole) {
            XZRuleMyselfVC *ruleMyselfVC = [[XZRuleMyselfVC alloc]init];
            ruleMyselfVC.groupId = self.groupId;
            //隐藏A标识
            ruleMyselfVC.type = @"GROUPDETAIL";
            [self.navigationController pushViewController:ruleMyselfVC animated:true];
        }else{
            XZRuleVC *ruleVC = [[XZRuleVC alloc]init];
             ruleVC.groupId = self.groupId;
            [self.navigationController pushViewController:ruleVC animated:true];
        }
    }else if ([model.GroupConfig.TimeType integerValue] == 2){
        if (!model.GroupConfig.IsManageRole) {
            XZMachineModeMyselfVC *machineModeMyselfVC = [[XZMachineModeMyselfVC alloc]init];
            machineModeMyselfVC.groupId = self.groupId;
            [self.navigationController pushViewController:machineModeMyselfVC animated:true];
        }else{
            XZMachineModeVC *machineModeVC = [[XZMachineModeVC alloc]init];
            machineModeVC.groupId = self.groupId;
            [self.navigationController pushViewController:machineModeVC animated:true];
            
        }
    }
    
}
#pragma mark - TableViewDataSource
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return (self.model.ResList.count > 0 && self.msgArray.count > 0)?2:1;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    self.tabView.mj_footer.hidden = self.msgArray.count > 0? NO:YES;
    if (self.model.ResList.count > 0 && self.msgArray.count > 0) {
        if (section == 0) {
            if (self.showResList) {
                return 3;
            }else{
               return self.model.ResList.count;
            }
        }else{
            return self.msgArray.count;
        }
    }else if (self.model.ResList.count > 0 && !(self.msgArray.count > 0)){
        if (self.showResList) {
            return 3;
        }else{
            return self.model.ResList.count;
        }
    }else if (!(self.model.ResList.count > 0) && self.msgArray.count > 0){
        return self.msgArray.count;
    }
    return 0;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    kWeakObject(self)
    if (self.model.ResList.count > 0 && self.msgArray.count > 0) {
        if (indexPath.section == 0) {
            GMMyClassCell *resListCell = [tableView dequeueReusableCellWithIdentifier:RESLISTCELL];
            GMMyclassModel * resListModel = self.model.ResList[indexPath.row];
            resListCell.model =resListModel;
            return resListCell;
        }else if (indexPath.section == 1){
            XZMemberCheckMsg *model = self.msgArray[indexPath.row];;
            XZMemberCheckMsgCell *msgCell = [tableView dequeueReusableCellWithIdentifier:MSGCELL];
            msgCell.model = model;
            msgCell.indexPath = indexPath;
            msgCell.parentController = self;
            //点赞
            msgCell.likeBlock = ^(XZMemberCheckMsg * _Nonnull model, NSIndexPath * _Nonnull indexPath) {
                [weakself likeContent:model refreshIndexPath:indexPath];
            };
            //消息读与未读
            msgCell.hasReadBlock = ^(NSInteger index, NSString * _Nonnull voiceID, NSString * _Nonnull voiceStr) {
               [weakself setVoiceRead:voiceID voiceIndex:index voiceType:voiceStr model:model];
            };
            return msgCell;
        }else{
            UITableViewCell  *cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"cell"];
            if (!cell) {
                cell = [[UITableViewCell alloc]initWithStyle:(UITableViewCellStyleDefault) reuseIdentifier:@"cell"];
            }
            return cell;
        }
    }else if (self.model.ResList.count > 0 && !(self.msgArray.count > 0)){
        GMMyClassCell *resListCell = [tableView dequeueReusableCellWithIdentifier:RESLISTCELL];
        GMMyclassModel * resListModel = self.model.ResList[indexPath.row];
        resListCell.model =resListModel;
        return resListCell;
    }else if (!(self.model.ResList.count > 0) && self.msgArray.count > 0){
        XZMemberCheckMsg *model = self.msgArray[indexPath.row];;
        XZMemberCheckMsgCell *msgCell = [tableView dequeueReusableCellWithIdentifier:MSGCELL];
        msgCell.model = model;
        msgCell.indexPath = indexPath;
        msgCell.parentController = self;
        //点赞
        msgCell.likeBlock = ^(XZMemberCheckMsg * _Nonnull model, NSIndexPath * _Nonnull indexPath) {
            [weakself likeContent:model refreshIndexPath:indexPath];
        };
        //消息读与未读
        msgCell.hasReadBlock = ^(NSInteger index, NSString * _Nonnull voiceID, NSString * _Nonnull voiceStr) {
            [weakself setVoiceRead:voiceID voiceIndex:index voiceType:voiceStr model:model];
        };
        
        return msgCell;
    }
    return nil;
}
#pragma mark - TableViewDelegate
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    if (self.model.ResList.count > 0 && self.msgArray.count > 0) {
        if (indexPath.section == 0) {
            return 80.f;
        }else if (indexPath.section == 1){
            XZMemberCheckMsg *model = self.msgArray[indexPath.row];
            return model.cellHeight;
        }
    }else if (self.model.ResList.count > 0 && !(self.msgArray.count > 0)){
        return 80.f;
    }else if (!(self.model.ResList.count > 0) && self.msgArray.count > 0){
        XZMemberCheckMsg *model = self.msgArray[indexPath.row];
        return model.cellHeight;
    }
    return 0.f;
}
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    if (self.model.ResList.count > 0 && self.msgArray.count > 0) {
        if (section == 0) {
            return 0.f;
        }else if (section == 1){
            return 40.f;
        }
    }else if (self.model.ResList.count > 0 && !(self.msgArray.count > 0)){
        return 0.f;
    }else if (!(self.model.ResList.count > 0) && self.msgArray.count > 0){
        return 40.f;
    }
    return 0.f;
}
- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{
    UIView *headView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, kScreenWidth, 40.f)];
    headView.backgroundColor = kWhiteColor;
    
    UIView *lineView = [[UIView alloc]initWithFrame:CGRectMake(0, 39.5, kScreenWidth, 0.5)];
    lineView.backgroundColor = kD7D7D7Color;
    [headView addSubview:lineView];
    
    UILabel *label = [[UILabel alloc]initWithFrame:CGRectMake(8, 10, 100, 20)];
    label.font = [UIFont systemFontOfSize:14.0f];
    label.textColor = kDarkGrayColor;
    label.text = @"消息区";
    [headView addSubview:label];
    
    UILabel *labe2 = [[UILabel alloc]initWithFrame:CGRectMake(kScreenWidth - 138, 10, 130, 20)];
    labe2.font = [UIFont systemFontOfSize:14.0f];
    labe2.textColor = kDarkGrayColor;
    labe2.textAlignment = NSTextAlignmentRight;
    labe2.text = [NSString stringWithFormat:@"共%lu条",(unsigned long)self.msgArray.count];
    [headView addSubview:labe2];
    
    return headView;
}
//还有多少未加载 点击显示全部
- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section{
    if (self.model.ResList.count > 0 && self.msgArray.count > 0) {
        if (section == 0) {
            if (self.showResList) {
                return 40.f;
            }else{
                return 0.f;
            }
        }else{
            return 0.f;
        }
    }else if (self.model.ResList.count > 0 && !(self.msgArray.count > 0)){
        if (self.showResList) {
            return 40.f;
        }else{
            return 0.f;
        }
    }else{
        return 0.f;
    }
    
}
-(UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section{
    //创建点击手势 点击显示全部资源
    UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(showAllResList)];
    UIView *resFootView = [[UIView alloc]init];
    [resFootView addGestureRecognizer:tap];
    resFootView.backgroundColor = kEFEFEFColor;
    UILabel *label = [[UILabel alloc]initWithFrame:CGRectMake(0, 0, kScreenWidth, 40.f)];
    label.font = [UIFont systemFontOfSize:14.0f];
    label.textColor = k1168E6Color;
    label.textAlignment = NSTextAlignmentCenter;
    label.text = [NSString stringWithFormat:@"还有%u个资源未显示，点击显示",self.model.ResList.count - 3];
    [resFootView addSubview:label];
    return resFootView;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    [tableView deselectRowAtIndexPath:indexPath animated:true];
    if (self.model.ResList.count>0 && self.msgArray.count > 0) {
        if (indexPath.section == 0) {
            GMMyclassModel *model = self.model.ResList[indexPath.row];
            [self resListJumpController:model];
        }
    }else if (self.model.ResList.count > 0 && !(self.msgArray.count > 0)){
        if (indexPath.section == 0) {
            GMMyclassModel *model = self.model.ResList[indexPath.row];
            [self resListJumpController:model];
        }
    }
}
/**
点击显示全部资源
 */
- (void)showAllResList{
    self.showResList = !self.showResList;
    [self.tabView reloadData];
}


/**
 语音读与未读

 @param voiceID 语音id
 @param index 所在的行
 @param voiceStr 区别是msg还是quote
 @param model 模型
 */
- (void)setVoiceRead:(NSString *)voiceID voiceIndex:(NSInteger)index voiceType:(NSString *)voiceStr model:(XZMemberCheckMsg *)model{
    NSDictionary *dict= @{@"from":FROM_IOS,
                          @"busiOrgId":[XGMArchiverTools cacheForKey:BUSIORGID],
                          @"loginFinger":[XGMArchiverTools cacheForKey:USER_identifierNumber],
                          @"userId":[XGMArchiverTools cacheForKey:USER_UserId],
                          @"voiceId":voiceID,
                          };
    kWeakObject(self)
    [MBProgressHUD showHUDAddedTo:weakself.view animated:YES];
    [HJNetwork HTTPWithMethod:HJRequestMethodPOST url:[NSString stringWithFormat:@"v30.teecloud.cn/ajax-api.ashx?$c=TeeyunApp&$m=PostVoiceReadStatus&$v=%@",VERSION] parameters:dict cachePolicy:HJCachePolicyIgnoreCache callback:^(id responseObject, NSError *error) {
        [MBProgressHUD hideHUDForView:weakself.view animated:YES];
        if (!error) {
            if ([[responseObject objectForKey:RESULT_NAME_Success] boolValue]) {
                if ([voiceStr isEqualToString:@"MSG"]) {
                    //MsgBody.VoiceList
                    for (NSInteger i=0; i<model.MsgBody.VoiceList.count; i++) {
                        GMVoiceListModel *temModel = model.MsgBody.VoiceList[i];
                        if (i == index) {
                            temModel.IsReaded =YES;
                        }
                    }
                }else{
                    //Quote.VoiceList
                    for (NSInteger i=0; i<model.Quote.VoiceList.count; i++) {
                        GMVoiceListModel *temModel = model.Quote.VoiceList[i];
                        if (i == index) {
                            temModel.IsReaded =YES;
                        }
                    }
                }
                [weakself.tabView reloadData];
            }else{
                [MBProgressHUD showErrorOrSuc:[responseObject objectForKey:RESULT_NAME_Message] toView:weakself.view];
            }
        }else{
            [MBProgressHUD showErrorOrSuc:@"请求出错" toView:weakself.view];
        }
    }];
}


/**
 资源区的跳转

 @param model 资源区模型
 */
- (void)resListJumpController:(GMMyclassModel *)model{
    //资源区的跳转
    if (model.NormalCode >0) {
        if (model.NormalCode ==1) {
            [MBProgressHUD showErrorOrSuc:@"关联资源已下架或不可用" toView:self.view];
        }else if (model.NormalCode ==2){
            [MBProgressHUD showErrorOrSuc:@"当前手机型 号非购买资源所用手机型号，你可以到“我的 - 主页 - 个人资料(付费资源管理)”模块申请变更手机型号。" toView:self.view];
        }else if (model.NormalCode ==3){
            [MBProgressHUD showErrorOrSuc:@"本期培训已结束，课件自动关闭；若有需要请报名参加下期培训。" toView:self.view];
        }
    }else{
        if ([model.ResType isEqualToNumber:@(1)]) {
            /**视频*/
            GMPlayerViewController *play = [[GMPlayerViewController alloc] init];
            play.groupId = self.groupId;
            play.resId = model.Id;
            [self.navigationController pushViewController:play animated:YES];
        }else if ([model.ResType isEqualToNumber:@(2)]){
            /**文档*/
            GMReadPDFVC *file = [[GMReadPDFVC alloc] init];
            file.resId = model.Id;
            file.groupId = self.groupId;
            [self.navigationController pushViewController:file animated:YES];
        }else if ([model.ResType isEqualToNumber:@(3)]){
            /**习题*/
            GMExercisesVC *exercises =[[GMExercisesVC alloc] init];
            exercises.resId = model.Id;
            exercises.groupId = self.groupId;
            [self.navigationController pushViewController:exercises animated:YES];
        }else if ([model.ResType isEqualToNumber:@(4)]){
            /**试卷*/
            GMExaminationVC *exam = [[GMExaminationVC alloc] init];
            exam.resId = model.Id;
            exam.groupId = self.groupId;
            [self.navigationController pushViewController:exam animated:YES];
        }else if ([model.ResType isEqualToNumber:@(9)]){
            /**课程包*/
            GMCoursePackageVC *package = [[GMCoursePackageVC alloc] init];
            package.resId = model.Id;
            package.titleStr = model.Name;
            package.groupId = self.groupId;
            [self.navigationController pushViewController:package animated:YES];
        }
    }
}
/**
 消息区点赞

 @param model 消息模型
 @param indexPath 给第几个点赞
 */
- (void)likeContent:(XZMemberCheckMsg *)model refreshIndexPath:(NSIndexPath *)indexPath{
    NSMutableDictionary *dict = [NSMutableDictionary dictionary];
    [dict setValue:FROM_IOS forKey:@"from"];
    [dict setValue:[XGMArchiverTools cacheForKey:BUSIORGID] forKey:@"busiOrgId"];
    [dict setValue:[XGMArchiverTools cacheForKey:USER_UserId] forKey:@"userId"];
    [dict setValue:[XGMArchiverTools cacheForKey:USER_identifierNumber] forKey:@"loginFinger"];
    [dict setValue:@(2) forKey:@"type"];
    [dict setValue:model.MsgBody.Id forKey:@"recId"];
    if (!model.MsgBody.IsLike) {
        [dict setValue:@(1) forKey:@"op"];//点赞
    }else{
        [dict setValue:@(2) forKey:@"op"];//取消点赞
    }
    kWeakObject(self)
    [MBProgressHUD showHUDAddedTo:self.view animated:YES];
    [HJNetwork POSTWithURL:[NSString stringWithFormat:@"ajax-api.ashx?$c=TeeyunApp&$m=LikeOrUnlike&$v=%@",VERSION] parameters:dict cachePolicy:HJCachePolicyIgnoreCache callback:^(id responseObject, NSError *error) {
        [MBProgressHUD hideHUDForView:weakself.view animated:YES];
        if (!error) {
            if ([[responseObject objectForKey:RESULT_NAME_Success] boolValue]) {
                NSString *msg =[responseObject objectForKey:RESULT_NAME_Message];
                if (msg != nil) {
                    [MBProgressHUD showErrorOrSuc:msg toView:weakself.view];
                }
                XZMemberCheckMsg *model = self.msgArray[indexPath.row];
                model.MsgBody.IsLike = !model.MsgBody.IsLike;
                NSInteger likeCount ;
                if (model.MsgBody.IsLike) {
                    likeCount = [model.MsgBody.LikeCount integerValue] + 1;
                }else{
                    likeCount = [model.MsgBody.LikeCount integerValue] - 1;
                }
                model.MsgBody.LikeCount = @(likeCount);
                //将之前的模型给替换
                [self.msgArray replaceObjectAtIndex:indexPath.row withObject:model];
                [self.tabView reloadRowsAtIndexPaths:[NSArray arrayWithObjects:indexPath, nil] withRowAnimation:UITableViewRowAnimationNone];
            }else{
                [MBProgressHUD showErrorOrSuc:[responseObject objectForKey:RESULT_NAME_Message] toView:weakself.view];
            }
        }else{
            [MBProgressHUD showErrorOrSuc:@"网络异常" toView:weakself.view];
        }
    }];
}
/**
 点击轮播的跳转
 
 @param model 轮播的模型
 */
- (void)clickNewsBannerIndex:(XZBannerTops *)model{
    [self updateReadCount:model.AdId];
    [self bannerSkipControllerWithNewsBanner:model];
}

/*
 *更新广告阅读计数
 */
-(void)updateReadCount:(NSString *)addId{
    NSMutableDictionary *dict = [NSMutableDictionary dictionary];
    [dict setValue:FROM_IOS forKey:@"from"];
    [dict setValue:[XGMArchiverTools cacheForKey:BUSIORGID] forKey:@"busiOrgId"];
    [dict setValue:[XGMArchiverTools cacheForKey:USER_UserId] forKey:@"userId"];
    [dict setValue:[XGMArchiverTools cacheForKey:USER_identifierNumber] forKey:@"loginFinger"];
    //广告Id
    [dict setValue:addId forKey:@"adId"];
    
    [HJNetwork POSTWithURL:[NSString stringWithFormat:@"/ajax-api.ashx?$c=TeeyunApp&$m=UpdateAdCount&$v=%@",VERSION] parameters:dict cachePolicy:HJCachePolicyIgnoreCache callback:^(id responseObject, NSError *error) {
        if (!error) {
            if ([[responseObject objectForKey:RESULT_NAME_Success] boolValue]) {
                XZLog(@"计数成功");
            }else{
                XZLog(@"计数失败");
            }
            
        }else{
            XZLog(@"%@",error);
        }
    }];
}
/*************************************轮播跳转******************************/
/**
 根据模型中RelType来进行跳转
 轮播
 @param model XZBannerTops
 */
- (void)bannerSkipControllerWithNewsBanner:(XZBannerTops *)model{
    if (1 == [model.RelType integerValue]) {//model.RelType=1
        [self bannerSkipRelTypeIsOne:model];
    }else if (2 == [model.RelType integerValue]){//model.RelType=2
        [self bannerSkipRelTypeIsTwo:model];
    }else if (3 == [model.RelType integerValue]){//新闻资讯案例
        XZNewsCaseVC *newsCaseVC = [[XZNewsCaseVC alloc]init];
        newsCaseVC.newsId = model.Id;
        [self.navigationController pushViewController:newsCaseVC animated:true];
    }else if (4 == [model.RelType integerValue]){//广告详情页面基地址
        NSString *adUrlString = [NSString stringWithFormat:@"%@/%@",URL_ADURL,model.Id];
        SFSafariViewController *sfVC = [[SFSafariViewController alloc]initWithURL:[NSURL URLWithString:adUrlString]];
        sfVC.title = model.Title;
        sfVC.delegate = self;
        [self presentViewController:sfVC animated:YES completion:nil];
    }
}
#pragma mark - SFSafariViewControllerDelegate -
- (void)safariViewControllerDidFinish:(SFSafariViewController *)controller{
    XZLog(@"击done");
}
/*
 *model.RelType=1 根据NormalCode  ResType IsAdded进行相应的跳转
 */
- (void)bannerSkipRelTypeIsOne:(XZBannerTops *)model{
    if (0 == [model.NormalCode integerValue]) {
        [self bannerSkipNormalCodeIsZeroControllerWithBannerTopsModel:model];
    }else if (1 == [model.NormalCode integerValue]){
        [MBProgressHUD showErrorOrSuc:@"关联资源已下架或不可用" toView:self.view];
    }else if (2 == [model.NormalCode integerValue]){
        [MBProgressHUD showErrorOrSuc:@"当前手机型号非购买资源所用手机型号，你可以到“我的 - 主页 - 个人资料(付费资源管理)”模块申请变更手机型号" toView:self.view];
    }
}
/*
 *当model.NormalCode=0时 根据ResType及IsAdded进行相应的跳转
 */
- (void)bannerSkipNormalCodeIsZeroControllerWithBannerTopsModel:(XZBannerTops *)model{
    if (1 == [model.ResType integerValue]) {//视频
        if (!model.IsFree) {
            GMBuyVideoVC *buyVideoVC = [[GMBuyVideoVC alloc]init];
            buyVideoVC.ResType = model.ResType;
            buyVideoVC.resId = model.Id;
        
            [self.navigationController pushViewController:buyVideoVC animated:true];
            //            [MBProgressHUD showErrorOrSuc:@"跳转”主页 - 资源 - 学习资源 - 试看(视频)“页面" toView:self.view];
        }else{
            GMPlayerViewController *playerVC = [[GMPlayerViewController alloc]init];
            playerVC.groupId = self.groupId;
            playerVC.resId = model.Id;
            [self.navigationController pushViewController:playerVC animated:true];
            //            [MBProgressHUD showErrorOrSuc:@"跳转”主页 - 我的 - 我的资源 - 播放 - 问题“页面" toView:self.view];
        }
    }else if (2 == [model.ResType integerValue]){//文档
        if (!model.IsFree) {
            GMBuyFile * buyFile = [[GMBuyFile alloc]init];
            buyFile.ResType = model.ResType;
         
            buyFile.resId = model.Id;
            [self.navigationController pushViewController:buyFile animated:true];
            //            [MBProgressHUD showErrorOrSuc:@"跳转”主页 - 资源 - 学习资源 - 详情(文档)“页面" toView:self.view];
        }else{
            GMReadPDFVC *myFileVC = [[GMReadPDFVC alloc]init];
            myFileVC.resId = model.Id;
            myFileVC.groupId = self.groupId;
            [self.navigationController pushViewController:myFileVC animated:true];
            //            [MBProgressHUD showErrorOrSuc:@"跳转”主页 - 我的 - 我的资源 - 文档“页面" toView:self.view];
        }
    }else if (3 == [model.ResType integerValue]){//习题
        if (!model.IsFree) {
            GMBuyFile *buyFile = [[GMBuyFile alloc]init];
            buyFile.ResType = model.ResType;
            buyFile.resId = model.Id;
          
            [self.navigationController pushViewController:buyFile animated:true];
            //            [MBProgressHUD showErrorOrSuc:@"跳转”主页 - 资源 - 学习资源 - 详情(习题、试卷)“页面" toView:self.view];
        }else{
            GMExercisesVC *exercisesVC = [[GMExercisesVC alloc]init];
            exercisesVC.resId = model.Id;
            exercisesVC.groupId= self.groupId;
            [self.navigationController pushViewController:exercisesVC animated:true];
            //            [MBProgressHUD showErrorOrSuc:@"跳转”主页 - 我的 - 我的资源 - 习题 - 答题“页面" toView:self.view];
        }
    }else if (4 == [model.ResType integerValue]){//试卷
        if (!model.IsFree) {
            GMBuyFile *buyFile = [[GMBuyFile alloc]init];
            buyFile.ResType = model.ResType;
          
            buyFile.resId = model.Id;
            [self.navigationController pushViewController:buyFile animated:true];
            //            [MBProgressHUD showErrorOrSuc:@"跳转”主页 - 资源 - 学习资源 - 详情(习题、试卷)“页面" toView:self.view];
        }else{
            GMExaminationVC * examinationVC = [[GMExaminationVC alloc]init];
            examinationVC.resId = model.Id;
            examinationVC.groupId = self.groupId;
            [self.navigationController pushViewController:examinationVC animated:true];
            //            [MBProgressHUD showErrorOrSuc:@"跳转”主页 - 我的 - 我的资源 - 试卷考试 - 考试须知“页面" toView:self.view];
        }
    }else if (9 == [model.ResType integerValue]){//课程包
        if (!model.IsFree) {
            GMBuyFile *buyFile = [[GMBuyFile alloc]init];
            buyFile.ResType = model.ResType;
          
            buyFile.resId = model.Id;
            [self.navigationController pushViewController:buyFile animated:true];
            //            [MBProgressHUD showErrorOrSuc:@"跳转”主页 - 资源 - 学习资源 - 详情(课程包)“页面" toView:self.view];
        }else{
            GMCoursePackageVC *coursePackageVC = [[GMCoursePackageVC alloc]init];
            coursePackageVC.groupId = self.groupId;
            coursePackageVC.resId = model.Id;
            coursePackageVC.titleStr = model.Title;
            [self.navigationController pushViewController:coursePackageVC animated:true];
            //            [MBProgressHUD showErrorOrSuc:@"跳转”主页 - 我的 - 我的资源 - 课程包“页面" toView:self.view];
        }
    }
}
/*
 *model.RelType=2 根据 IsAdded进行相应的跳转
 */
- (void)bannerSkipRelTypeIsTwo:(XZBannerTops *)model{
    if (!model.IsAdded) {
        XZGroupIntroduceVC *groupIntroduceVC = [[XZGroupIntroduceVC alloc]init];
        groupIntroduceVC.titileStr = model.Title;
        groupIntroduceVC.groupId = model.Id;
        [self.navigationController pushViewController:groupIntroduceVC animated:true];
    }else{
        XZMyGroupDetailVC *myGroupDetailVC = [[XZMyGroupDetailVC alloc]init];
        myGroupDetailVC.titleStr = model.Title;
        myGroupDetailVC.groupId = model.Id;
        [self.navigationController pushViewController:myGroupDetailVC animated:true];
    }
}
#pragma mark - setter
- (XZMyGroupDetailHeadView *)headView{
    if (!_headView) {
        _headView = [[XZMyGroupDetailHeadView alloc]initWithFrame:CGRectMake(0, 0, DEVICE_WIDTH, 100)];
        _headView.delegate = self;
    }
    return _headView;
}
- (UITableView *)tabView{
    if (!_tabView) {
        _tabView = [[UITableView alloc]initWithFrame:CGRectMake(0, 0, DEVICE_WIDTH, DEVICE_HEIGHT-kNavBarAndStatusBarHeight-kBottomSafeHeight-50) style:UITableViewStylePlain];
        _tabView.delegate = self;
        _tabView.dataSource = self;
        _tabView.showsVerticalScrollIndicator =false;
        _tabView.separatorStyle =UITableViewCellSeparatorStyleNone;
        //资源 消息cell注册
        [_tabView registerNib:[UINib nibWithNibName:NSStringFromClass([GMMyClassCell class]) bundle:nil] forCellReuseIdentifier:RESLISTCELL];
        [_tabView registerNib:[UINib nibWithNibName:NSStringFromClass([XZMemberCheckMsgCell class]) bundle:nil] forCellReuseIdentifier:MSGCELL];
        //上下拉刷新
        _tabView.mj_header = [MJRefreshNormalHeader headerWithRefreshingTarget:self refreshingAction:@selector(getGroupMsgList)];
        _tabView.mj_footer = [MJRefreshAutoNormalFooter footerWithRefreshingTarget:self refreshingAction:@selector(getMoreGroupMsgList)];
        _tabView.mj_footer.hidden =YES;
        [self.view addSubview:_tabView];
    }
    return _tabView;
}
//消息区数组
- (NSMutableArray *)msgArray{
    if (!_msgArray) {
        _msgArray = [[NSMutableArray alloc]init];
    }
    return _msgArray;
}
//菜单图片数组
- (NSMutableArray *)menuIconArray{
    if (!_menuIconArray) {
        _menuIconArray =[[NSMutableArray alloc]init];
    }
    return _menuIconArray;
}
//菜单文字数组
- (NSMutableArray *)menuTitleArray{
    if (!_menuTitleArray) {
        _menuTitleArray =[[NSMutableArray alloc]init];
    }
    return _menuTitleArray;
}


/**
 评论

 @param sender 手势
 */
- (IBAction)commentTapAction:(UITapGestureRecognizer *)sender {
    XZGroupDetailPopVC *commentVC = [[XZGroupDetailPopVC alloc] init];
    commentVC.model = self.model;
    commentVC.groupId = self.groupId;
    [self.navigationController presentSemiViewController:commentVC withOptions:@{
                                                                                 KNSemiModalOptionKeys.pushParentBack    : @(NO),
                                                                                 KNSemiModalOptionKeys.animationDuration : @(0.5),
                                                                                 KNSemiModalOptionKeys.shadowOpacity     : @(0.3)
                                                                                 }];
}


@end
